﻿// --------------------------------------------------------
// <copyright file="GeetestController.cs" company="ChiakiYu">
//     Copyright (c) 2015-2017 ChiakiYu.All rights reserved
// </copyright >
// <creation-date>2017-03-29 13:45</creation-date>
// <last-editor>于琦(yu_199012@qq.com)</last-editor>
// <last-date>2017-03-29 16:37</last-date>
// --------------------------------------------------------

using System.Web.Mvc;
using MvcDemo.Models.Geetest;

namespace MvcDemo.Controllers
{
    public class GeetestController : Controller
    {
        public ActionResult Geetest()
        {
            var loginInfo = new LoginInfo();
            return View(loginInfo);
        }

        [HttpPost]
        public ActionResult Geetest(LoginInfo loginInfo)
        {
            if (!ModelState.IsValid)
            {
                ViewData["message"] = "请填写完整数据";
                return View(loginInfo);
            }
            if (!IsVerifyCaptcha())
            {
                ViewData["message"] = "验证码错误";
                return View(loginInfo);
            }
            if (loginInfo.UserName == "admin" && loginInfo.Password == "123123")
            {
                ViewData["message"] = "登录成功";
                return View(loginInfo);
            }
            ViewData["message"] = "用户名密码错误";
            return View(loginInfo);
        }

        /// <summary>
        ///     验证码是否正确
        /// </summary>
        /// <returns></returns>
        public bool IsVerifyCaptcha()
        {
            var geetest = new GeetestLib(GeetestConfig.PublicKey, GeetestConfig.PrivateKey);
            var gtServerStatusCode = (byte) Session[GeetestLib.GtServerStatusSessionKey];
            var challenge = Request.Form.Get(GeetestLib.FnGeetestChallenge);
            var validate = Request.Form.Get(GeetestLib.FnGeetestValidate);
            var seccode = Request.Form.Get(GeetestLib.FnGeetestSeccode);
            var result = gtServerStatusCode == 1
                ? geetest.EnhencedValidateRequest(challenge, validate, seccode)
                : geetest.FailbackValidateRequest(challenge, validate, seccode);
            return result == 1;
        }

        /// <summary>
        ///     获取验证码
        /// </summary>
        /// <returns></returns>
        public ContentResult GetCaptcha()
        {
            var geetest = new GeetestLib(GeetestConfig.PublicKey, GeetestConfig.PrivateKey);
            var gtServerStatus = geetest.PreProcess();
            Session[GeetestLib.GtServerStatusSessionKey] = gtServerStatus;
            return Content(geetest.GetResponseStr());
        }
    }
}